
package com.suishenbaodian.saleshelper.wxapi;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;

import com.squareup.picasso.Picasso;
import com.suishenbaodian.saleshelper.Constants;
import com.suishenbaodian.saleshelper.R;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class WXEntryActivity extends Activity implements IWXAPIEventHandler {
    private IWXAPI wx_api;
    private ImageView mIvHead;
    private TextView mTvName;

    /**
     * handler
     **/
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    String body = (String) msg.obj;
                    try {
                        JSONObject jsonObject = new JSONObject(body);
                        String nickName = jsonObject.getString("nickname");
                        String headimgurl = jsonObject.getString("headimgurl");
                        String sex = jsonObject.getString("sex");
                        Picasso.with(WXEntryActivity.this).load(headimgurl).into(mIvHead);
                        mTvName.setText(nickName + "  " +sex);

                        Log.i("WXTest","getUserInfo OK");
                        Log.i("WXTest","getUserInfo == " + body);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                case 1:

                    break;

                }
            super.handleMessage(msg);
        }
    };
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.wx_layout);
        mIvHead = (ImageView) findViewById(R.id.iv_wx);
        mTvName = (TextView) findViewById(R.id.tv_wx_name);

        wx_api = WXAPIFactory.createWXAPI(WXEntryActivity.this, Constants.APP_ID, true);
        wx_api.registerApp(Constants.APP_ID);
        wx_api.handleIntent(getIntent(), WXEntryActivity.this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        wx_api.handleIntent(intent, WXEntryActivity.this);
        Log.i("WXTest","onNewIntent ");
    }

    @Override
    public void onReq(BaseReq baseReq) {
        Log.i("WXTest","onReq");
    }

    @Override
    public void onResp(BaseResp resp) {
        switch (resp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                Log.i("WXTest","onResp OK");
                if(resp instanceof SendAuth.Resp){
                    SendAuth.Resp newResp = (SendAuth.Resp) resp;
                    //获取微信传回的code
                    String code = newResp.code;
                    Log.i("WXTest","onResp code = "+code);
                    getToken(code);
                }

                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                Log.i("WXTest","onResp ERR_USER_CANCEL ");
                //发送取消
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                Log.i("WXTest","onResp ERR_AUTH_DENIED");
                //发送被拒绝
                break;
            default:
                Log.i("WXTest","onResp default errCode " + resp.errCode);
                //发送返回
                break;
        }
    }


    private void getToken(String code){
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(3000, TimeUnit.MILLISECONDS)
                .writeTimeout(3000, TimeUnit.MILLISECONDS)
                .readTimeout(3000, TimeUnit.MILLISECONDS)
                .build();
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+ Constants.APP_ID+"&secret="+Constants.APPSECRET+"&code=" +code+"&grant_type=authorization_code";
        Request requests = new Request.Builder().url(url)
                .tag(this).build();

        okHttpClient.newCall(requests).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i("WXTest","getToken onFailure");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    String body = response.body().string();
                    JSONObject object  = new JSONObject(body);
                    String mAccess_token = object.getString("access_token");
                    String mOpenId = object.getString("openid");
                    getUserInfo(mAccess_token,mOpenId);
                    Log.i("WXTest","getToken OK");
                    Log.i("WXTest","getToken = " + mAccess_token);

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });

    }

    //获取到token和openID之后，调用此接口得到身份信息
    private void getUserInfo(String token,String openID){

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(3000, TimeUnit.MILLISECONDS)
                .writeTimeout(3000, TimeUnit.MILLISECONDS)
                .readTimeout(3000, TimeUnit.MILLISECONDS)
                .build();

        String url = "https://api.weixin.qq.com/sns/userinfo?access_token=" +token+"&openid=" +openID;
        Request requests = new Request.Builder().url(url)
                .tag(this).build();

        okHttpClient.newCall(requests).enqueue(new Callback() {
            @Override

            public void onFailure(Call call, IOException e) {
                Log.i("WXTest","getUserInfo onFailure");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                String body = response.body().string();
                Message message = mHandler.obtainMessage();
                message.what = 0;
                message.obj = body;
                mHandler.sendMessage(message);

            }
        });
    }
}
